package com.zzzyh.forumsystemclient.cotroller;

import com.alibaba.fastjson.JSON;
import com.zzzyh.forumsystemclient.common.AppResult;
import com.zzzyh.forumsystemclient.common.ResultCode;
import com.zzzyh.forumsystemclient.model.*;
import com.zzzyh.forumsystemclient.services.*;
import com.zzzyh.forumsystemclient.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/article")
@Slf4j
public class ArticleController {
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserArticleService userArticleService;
    @Autowired
    private IBoardService boardService;
    @Autowired
    private IArticle_BoardService article_boardService;

    @RequestMapping("/getArticles")
    public AppResult<PageResult<Article>> getArticles(@RequestBody PageRequest pageRequest) {
        PageResult<Article> articles = articleService.getArticles(pageRequest);
        return AppResult.success(articles);
    }

    @RequestMapping("/gerUserIdByArticleId")
    public AppResult<Long> gerUserIdByArticleId(@RequestParam("articleId") Long articleId) {
        Long userId = articleService.gerUserIdByArticleId(articleId);
        return AppResult.success(userId);
    }


    @RequestMapping("/getArticleByArticleId")
    public AppResult<Article> getArticleByArticleId(@RequestParam("articleId") Long articleId) {
        Article article = articleService.getArticleByArticleId(articleId);
        if (article == null)
            return AppResult.failed(ResultCode.FAILED_DB_ERROR);
        article.setUser(userService.selectUserByUserId(article.getUserId()));
        log.info("article:{}",article);
        List<Article_Board> boardsByArticleId = article_boardService.getBoardsByArticleId((articleId));
        log.info("boardsByArticleId:{}",boardsByArticleId);
        article.setTags(new ArrayList<>());
        for (Article_Board  articleBoard : boardsByArticleId){
            Board board = boardService.getBoardById(articleBoard.getBoardId());
            article.getTags().add(board.getName());
        }
        return AppResult.success(article);
    }

//    @RequestMapping("/getArticlesByBoard")

    @RequestMapping("/createArticle")
    public AppResult<Long> createArticle(@RequestBody Article article,@RequestHeader("Authorization") String token) {
        String userString = JwtUtils.getSubjectFromToken(token);
        LoginUser loginUser = JSON.parseObject(userString, LoginUser.class);
        article.setUserId(loginUser.getUser().getId());
        articleService.createArticle(article);
        User user = userService.selectUserByUserId(article.getUserId());
        user.setArticleCount(user.getArticleCount() + 1);
        userService.updateUser(user);
        User_Article userArticle = new User_Article();
        userArticle.setUserId(article.getUserId());
        userArticle.setArticleId(article.getId());
        userArticle.setRelationship(0);
        userArticleService.insetUserArticle(userArticle);
        List<String> tags = article.getTags();
        if(tags != null){
            for(String tag:tags){
                Board board = boardService.getBoardByBoardname(tag);
                if(board != null){
                    Article_Board boardArticle = article_boardService.getBoardArticle(article.getId(), board.getId());
                    if(boardArticle != null){
                        board.setArticleCount(board.getArticleCount() + 1);
                        boardArticle.setIsDelete((byte) 0);
                        article_boardService.updateArticle_Board(boardArticle);
                    }else{
                        boardArticle = new Article_Board();
                        boardArticle.setArticleId(article.getId());
                        boardArticle.setBoardId(board.getId());
                        board.setArticleCount(board.getArticleCount() + 1);
                        article_boardService.createArticle_Board(boardArticle);
                    }
                    boardService.updateBoard(board);
                }else{
                    board = new Board();
                    board.setName(tag);
                    board.setArticleCount(1);
                    boardService.createBoard(board);
                    Article_Board boardArticle = new Article_Board();
                    boardArticle.setArticleId(article.getId());
                    boardArticle.setBoardId(board.getId());
                    article_boardService.createArticle_Board(boardArticle);
                }
            }
        }
        return AppResult.success(article.getId());
    }

    @RequestMapping("/updateArticle")
    public AppResult<Void> UpdateArticle(@RequestBody Article article,@RequestHeader("Authorization") String token) {
        String userString = JwtUtils.getSubjectFromToken(token);
        LoginUser loginUser = JSON.parseObject(userString, LoginUser.class);
        article.setUserId(loginUser.getUser().getId());
        if(article.getUserId() == null ||loginUser.getUser().getId() == null ||
                !article.getUserId().equals(loginUser.getUser().getId())){
            log.info("{},{}",article.getUserId(),loginUser.getUser().getId());
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        log.info("article:{}",article);
        articleService.updateArticle(article);
        log.info("article:{}",article);
        Set<String> currentTagsSet = new HashSet<>(article.getTags());
        Set<String> oldTagsSet = new HashSet<>(article.getOldTags());
        // 找出新增的标签：tags - oldTags
        Set<String> addedTags = new HashSet<>(currentTagsSet);
        addedTags.removeAll(oldTagsSet);

        // 找出删除的标签：oldTags - tags
        Set<String> removedTags = new HashSet<>(oldTagsSet);
        removedTags.removeAll(currentTagsSet);

//        // 找出未变化的标签：tags ∩ oldTags
//        Set<String> unchangedTags = new HashSet<>(currentTagsSet);
//        unchangedTags.retainAll(oldTagsSet);

        log.info("addedTags:{},removedTags:{}",addedTags,removedTags);
        for (String tag : addedTags) {
            Board board = boardService.getBoardByBoardname(tag);
            if(board != null){
                Article_Board boardArticle = article_boardService.getBoardArticle(article.getId(), board.getId());
                if(boardArticle != null){
                    board.setArticleCount(board.getArticleCount() + 1);
                    boardArticle.setIsDelete((byte) 0);
                    article_boardService.updateArticle_Board(boardArticle);
                }else{
                    boardArticle = new Article_Board();
                    boardArticle.setArticleId(article.getId());
                    boardArticle.setBoardId(board.getId());
                    board.setArticleCount(board.getArticleCount() + 1);
                    article_boardService.createArticle_Board(boardArticle);
                }
                boardService.updateBoard(board);
            }else{
                board = new Board();
                board.setName(tag);
                board.setArticleCount(1);
                boardService.createBoard(board);
                Article_Board boardArticle = new Article_Board();
                boardArticle.setArticleId(article.getId());
                boardArticle.setBoardId(board.getId());
                article_boardService.createArticle_Board(boardArticle);
            }
        }
        for (String tag : removedTags) {
            Board board = boardService.getBoardByBoardname(tag);
            if(board != null){
                Article_Board boardArticle = article_boardService.getBoardArticle(article.getId(), board.getId());
                if(boardArticle == null){
//                    board.setArticleCount(board.getArticleCount() - 1);
                }else{
                    board.setArticleCount(board.getArticleCount() - 1);
                    if(board.getArticleCount() <= 0)
                        board.setIsDelete((byte) 1);
                    boardArticle.setIsDelete((byte) 1);
//                    article_boardService.createArticle_Board(boardArticle);
                    article_boardService.updateArticle_Board(boardArticle);
                }
                boardService.updateBoard(board);
            }else{
            }
        }
        return AppResult.success();
    }

    @RequestMapping("/deleteArticle")
    public AppResult<Void> deleteArticle(@RequestParam("articleId") Long articleId,@RequestHeader("Authorization") String token) {
        String userString = JwtUtils.getSubjectFromToken(token);
        LoginUser loginUser = JSON.parseObject(userString, LoginUser.class);
        Article article = articleService.getArticleByArticleId(articleId);
        if(article == null || article.getUserId() == null ||loginUser.getUser().getId() == null ||
                !article.getUserId().equals(loginUser.getUser().getId())){
            log.info("{},{}",article.getUserId(),loginUser.getUser().getId());
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        articleService.deleteArticle(articleId);
        User user = userService.selectUserByUserId(article.getUserId());
        user.setArticleCount(user.getArticleCount() - 1);
        userService.updateUser(user);

        List<Article_Board> boardArticles = article_boardService.getBoardsByArticleId(articleId);
        List<String> tags = new ArrayList<>();
        for (Article_Board boardArticle : boardArticles) {
            Board boardById = boardService.getBoardById(boardArticle.getBoardId());
            tags.add(boardById.getName());
        }
        for (String tag : tags) {
            Board board = boardService.getBoardByBoardname(tag);
            if(board != null){
                Article_Board boardArticle = article_boardService.getBoardArticle(article.getId(), board.getId());
                if(boardArticle == null){
//                    board.setArticleCount(board.getArticleCount() - 1);
                }else{
                    board.setArticleCount(board.getArticleCount() - 1);
                    if(board.getArticleCount() <= 0)
                        board.setIsDelete((byte) 1);
                    boardArticle.setIsDelete((byte) 1);
//                    article_boardService.createArticle_Board(boardArticle);
                    article_boardService.updateArticle_Board(boardArticle);
                }
                boardService.updateBoard(board);
            }else{
            }
        }

        return AppResult.success();
    }

    @RequestMapping("/getArticlesByUserId")
    AppResult<List<Article>> getArticlesByUserId(@RequestParam("userId") Long userId) {
        List<Article> articles = articleService.getArticlesByUserId(userId);
        return AppResult.success(articles);
    }

    @RequestMapping("/searchArticles")
    AppResult<List<Article>> searchArticles(@RequestParam("keyword") String keyword) {
        log.info("搜索关键字：{}", keyword);
        List<Article> articles = articleService.searchArticles(keyword);
        for (Article article : articles){
            article.setUser(userService.selectUserByUserId(article.getUserId()));
        }
        return AppResult.success(articles);
    }

    @RequestMapping("/boardArticles")
    AppResult<List<Article>> boardArticles(@RequestParam("boardId") Long boardId) {
        if(boardId == 0)
            return AppResult.success();
        List<Article> articles = new ArrayList();
        for (Long l : article_boardService.getArticleIdsByBoardId(boardId)) {
            Article article = articleService.getArticleByArticleId(l);
            article.setUser(userService.selectUserByUserId(article.getUserId()));
            articles.add(article);
        }
        return AppResult.success(articles);
    }

}
